package cn.org.timespace.ons.action.base;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.ActionContext;

import cn.org.timespace.easyframe.action.EFBaseAction;
import cn.org.timespace.ons.service.base.AppleServerService;
import cn.org.timespace.ons.service.base.MachinesApplyService;
import cn.org.timespace.ons.service.base.MachinesService;
import cn.org.timespace.ons.service.base.TypeAuditService;
import cn.org.timespace.ons.service.base.UserMachineTypeService;
import cn.org.timespace.ons.util.datatime.DateTimeUtils;
import cn.org.timespace.ons.util.pager.Pager;
import cn.org.timespace.ons.util.pager.PagerHelper;
import cn.org.timespace.ons.vo.base.Machines;
import cn.org.timespace.ons.vo.base.MachinesApply;
import cn.org.timespace.ons.vo.base.Options;
import cn.org.timespace.ons.vo.base.TypeAudit;
import cn.org.timespace.ons.vo.base.UserMachineType;


public class TypeAuditAction extends EFBaseAction{
	
	private static final long serialVersionUID = -3416183313291298070L;
	private static Log log = LogFactory.getLog(TypeAuditAction.class);
	private TypeAuditService typeAuditService;
    private static String LISTAPPLY ="listapply";
    private AppleServerService appleServerService;
    private UserMachineTypeService  userMachineTypeService;
    private MachinesService machinesService;
    private MachinesApplyService machinesApplyService; 
	public MachinesApplyService getMachinesApplyService() {
		return machinesApplyService;
	}

	public void setMachinesApplyService(MachinesApplyService machinesApplyService) {
		this.machinesApplyService = machinesApplyService;
	}

	public MachinesService getMachinesService() {
		return machinesService;
	}

	public void setMachinesService(MachinesService machinesService) {
		this.machinesService = machinesService;
	}

	public AppleServerService getAppleServerService() {
		return appleServerService;
	}

	public void setAppleServerService(AppleServerService appleServerService) {
		this.appleServerService = appleServerService;
	}
	
	public TypeAuditService getTypeAuditService() {
		return typeAuditService;
	}

	public void setTypeAuditService(TypeAuditService typeAuditService) {
		this.typeAuditService = typeAuditService;
	}
	public TypeAuditAction()
	{
		super(new TypeAuditModel());
	}	
	TypeAuditModel typeAuditModel = (TypeAuditModel) this.getModel();
	

	/**
	 * 我的审核
	 * 显示当前登录用户 所对应的审核人员信息
	 * @return
	 * @throws Exception
	 */
	public String doList() throws Exception{
		
	    String endUserName = getUserAccount();
	    
	    //
    	typeAuditModel.setEndUserName(endUserName);
    	
    	Pager p = PagerHelper.getPagerInstance(getRequest());
    	if(typeAuditModel.getStatus()==null){
    		typeAuditModel.setStatus(1);
		}
		List<Object> resList = typeAuditService.findByCondition(typeAuditModel,p);
		
		if(resList != null && resList.size() == 2){
			p.setTotalCount(((Integer)resList.get(0)));
			p.setData((List)resList.get(1));
		}
		
		return LIST;
	}
	
	
	/**
	 * 我的申请
	 * 显示前登录用户且状态不为取消的信息
	 * 1为取消状态 将不会被显示在页面上
	 * @return
	 * @throws Exception
	 */
	public String doListMyApply() throws Exception{
		
	    String startUserName = getUserAccount();
	    typeAuditModel.setStartUserName(startUserName);
	    Pager p = PagerHelper.getPagerInstance(getRequest());
	    if(typeAuditModel.getStatus()==null){
	    	typeAuditModel.setStatus(1);
	    }
		List<Object> resList = typeAuditService.findByCondition(typeAuditModel,p);
		if(resList != null && resList.size() == 2){
			p.setTotalCount(((Integer)resList.get(0)));
			p.setData((List)resList.get(1));
		  }
		List<UserMachineType> list = this.findByUserName(startUserName);
		Map request = (Map)ActionContext.getContext().get("request");
		request.put("list",list);
		return "myapply";
	    }
	/**
	 * 我的申请
	 * 批量的对我的申请进行 取消操作
	 * @return
	 * @throws Exception
	 */
	public String doChageMyApply()throws Exception{
		
		String id = getRequest().getParameter("theId");
		String status = getRequest().getParameter("status1") ;
		String[] mid = id.split(",");
		doCanceApply(mid,status);
		return doListMyApply();
	}
	
	
	/**
	 * 根据status的值不如，操作不同的状态
	 * 0:通过1：未审核2：不通过3：取消
	 * 批量操作公用方法
	 * @return
	 * @throws Exception
	 */
	public String doCanceApply(String[] mid,String status){
		
		if(mid.length>0){
			for(int i = 0 ; i<mid.length ; i++){
				if(mid[i] != null && mid[i] != "" && !"".equals(mid[i])){
					TypeAudit typeAudit = typeAuditService.findById(mid[i]);
					typeAudit.setStatus(Integer.parseInt(status));
					typeAuditService.update(typeAudit);
					//审核通过保存信息终端与应用平台对应
					if(status.equals("0")){
						//列出该信息终端类型下的所有信息终端
						MachinesModel machinesModel =  new MachinesModel();
						machinesModel.setTheIdMachine(typeAudit.getTheIdmachine());
						//machinesModel.setStatus("1");
						List<Machines> resList = machinesService.findByCondition(machinesModel);
						for(int n=0;n<resList.size();n++){
							//根据信息终端ID和应用平台ID查询machinesApply表，如果没有记录就插入一条新记录
							MachinesApplyModel model = new MachinesApplyModel();
							model.setMsid(typeAudit.getTheIdmachine());//信息终端
							model.setAsid(typeAudit.getTheIdapply());//应用平台ID
							List<MachinesApply> list = machinesApplyService.findByCondition(model);
							System.out.println(list.size());
							if(list.size()==0){
								//保存记录
								MachinesApply macnew = new MachinesApply();
								macnew.setMsid(typeAudit.getTheIdmachine());//信息终端
								macnew.setAsid(typeAudit.getTheIdapply());//应用平台ID
								macnew.setStatus(0);
								macnew.setSentTime(new Date());
								macnew.setStartUserName(typeAudit.getStartUserName());
								machinesApplyService.save(macnew);
							}
							
						}
						
					}
				}
			}
		}
		return "";
	}
	/**
	 * 我的审核
	 * 批量的对我的审核进行操作 
	 * 1未审核
	 * 2审核不通过
	 * 0审核通过
	 * @return
	 * @throws Exception
	 */
	public String doApply() throws Exception{
	
		String id = getRequest().getParameter("theId");
		String status = getRequest().getParameter("status1") ;
		String[] mid = id.split(",");
		doCanceApply(mid,status);
		
		return doList();
	}

	
	//我的申请先列出现有的应用，先有应用在我的终端类型里没有记录
	public String doMyApply() throws Exception{
		
		Pager p = PagerHelper.getPagerInstance(getRequest());

		 String idandusername = getRequest().getParameter("nid");
		 String theidname[] = idandusername.split(",");
		 String machine[] = theidname[0].split("-");
		List<Object> resList = appleServerService.findAppByCondition(machine, p);
		
		if(resList != null && resList.size() == 2){
			p.setTotalCount(((Integer)resList.get(0)));
			p.setData((List)resList.get(1));
		}
		getRequest().setAttribute("idname", idandusername);//保存信息终端类型ID和用户ID
		return LISTAPPLY;
	}
	//保存我的申请
	public String doSave() throws Exception{
		//信息终端类型ID和用户名
		String idandusername = getRequest().getParameter("idandusername");
		//应用平台ID和用户名
		String machinesString = getRequest().getParameter("machinesString");
		
		//解析idandusername应用类型格式：id|name,id|name
		PrintWriter out;
		getResponse().setCharacterEncoding("UTF-8");
		String[] idname = idandusername.split(",");//解析后的格式是id|name
		String[] machinesid = machinesString.split(",");
		
		boolean flag = false;
		//循环信息终端类型
		for(String id:idname){
			//解析idname
			String theidname[] = id.split("-");
			TypeAudit typeAudit  = new TypeAudit();
			
			for(String theid:machinesid){
				System.out.println(theid);
				String apply[] = theid.split("-");
				typeAudit.setStartUserName(theidname[1]);
				typeAudit.setEndUserName(apply[1]);
				typeAudit.setSentTime(new Date());
				typeAudit.setStatus(1);
				typeAudit.setTheIdapply(apply[0]);
				typeAudit.setTheIdmachine(theidname[0]);
				//保存之前先判断该申请有没有，如果有的话则不让保存，如果没有的话则保存
				if(!userMachineTypeService.findTypeAuditByCondition(apply[0],theidname[0],  theidname[1])){
					flag = typeAuditService.save(typeAudit);
				}
			}
			
		}
		
		if(flag){
			out = getResponse().getWriter();
			out.write("1");
		}
		
		
		return null;
	}

	public UserMachineTypeService getUserMachineTypeService() {
		return userMachineTypeService;
	}

	public void setUserMachineTypeService(
			UserMachineTypeService userMachineTypeService) {
		this.userMachineTypeService = userMachineTypeService;
	}
	/**
	 * 类型下拉列表的选项
	 * @return
	 * @throws Exception
	 */
	public List<UserMachineType> findByUserName(String userName) throws Exception{
		List<UserMachineType> list = this.userMachineTypeService.findByUserName(userName);
		
		return list;
	}
}
